# Copyright (c) 2011, the Dart project authors.  Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.

# TODO(jimhug): Move this and other gen files into Dart.

HEADER = '''// Copyright (c) 2011, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// Generated by %s.

'''

EXT = '.g.dart'

class CodeWriter:
  '''Helper class for generating source code.  The main purpose right now
  is to keep track of indentation for pretty printing.  In the future
  much more could be added here - but I'd rather wait until we can write
  this directly in Dart.
  '''
  def __init__(self, genfile):
    self._text = []
    self._indent = 0
    self._genfile = genfile

  def enterBlock(self, text=None):
    if text is not None: self.writeln(text)
    self._indent += 1

  def exitBlock(self, text=None):
    assert self._indent > 0
    self._indent -= 1
    if text is not None: self.writeln(text)

  def writeIndent(self):
    self._text.append('  ' * self._indent)

  def writeln(self, s=None, *args):
    if not s:
      self._text.append('\n')
      return

    self.writeIndent()
    if args:
      self._text.append(s % args)
    else:
      self._text.append(s)
    self._text.append('\n')

  def __str__(self):
    return ''.join(self._text)

  def writeToFile(self, filename):
    with open(filename + EXT, 'w') as f:
      f.write(HEADER % self._genfile)
      for line in self._text:
        f.write(line)